<template>
    <div class="register-container">
      <NavBar>
        <template #default> 注册 </template>
      </NavBar>

      <div class="register-content">
        <div class="logo">
          <el-icon color="#ff5000" :size="60">
            <ShoppingTrolley />
          </el-icon>
        </div>

        <div class="register-form">
          <div class="input-container">
            <el-input
              v-model="userName"
              placeholder="请输入账号"
              class="custom-input"
              :prefix-icon="User"
              clearable
            />
          </div>

          <div class="input-container">
            <el-input
              v-model="userPassword"
              placeholder="请输入密码"
              type="password"
              class="custom-input"
              :prefix-icon="Lock"
              show-password
              clearable
            />
          </div>

          <div class="input-container">
            <el-input
              v-model="confirmPassword"
              placeholder="请再次输入密码"
              type="password"
              class="custom-input"
              :prefix-icon="Lock"
              show-password
              clearable
            />
          </div>

          <div class="input-container">
            <el-input
              v-model="mobile"
              placeholder="请输入手机号 (可选)"
              class="custom-input"
              :prefix-icon="Iphone"
              clearable
            />
          </div>

          <div class="input-container">
            <el-input
              v-model="email"
              placeholder="请输入邮箱 (可选)"
              class="custom-input"
              :prefix-icon="Message"
              clearable
            />
          </div>

          <div class="input-container gender-select-container">
            <el-select
              v-model="gender"
              placeholder="请选择性别 (可选)"
              class="custom-select"
            >
              <el-option label="未知" :value="0" />
              <el-option label="男" :value="1" />
              <el-option label="女" :value="2" />
            </el-select>
          </div>

          <div class="input-container avatar-upload-container">
            <el-upload
              class="avatar-uploader"
              action="#"
              :show-file-list="false"
              :auto-upload="false"
              :on-change="handleAvatarChange"
              :limit="1"
            >
              <img v-if="avatarPreview" :src="avatarPreview" class="avatar" />
              <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
            </el-upload>
            <span class="upload-tip">点击上传头像 (可选)</span>
          </div>

          <el-button
            class="register-btn"
            type="primary"
            @click="handleRegister"
            :loading="isRegistering"
          >
            注册
          </el-button>
          <br />
          <br />
          <el-button class="login-back-btn" @click="goToLogin">
            已有账号，去登录
          </el-button>
        </div>
      </div>

      <div class="bottom-cover">
        <div class="bottom-links">
          <span @click="goToAbout">关于</span>
          <span class="divider">|</span>
          <span @click="goToResetPassword">找回密码</span>
        </div>
      </div>
    </div>
  </template>

  <script setup>
  import NavBar from "../../components/common/NavBar.vue";
  import { ref } from "vue";
  import {
    ShoppingTrolley,
    User,
    Lock,
    Iphone,
    Message,
    Plus,
  } from "@element-plus/icons-vue";
  import router from "@/router";
  import { ElMessage } from "element-plus";

  // 导入 Pinia user store
  import { useUserStore } from "@/stores/user";

  // 表单数据
  const userName = ref("zy");
  const userPassword = ref("aaaaaa");
  const confirmPassword = ref("aaaaaa");
  const mobile = ref("15386490869"); // 新增手机号
  const email = ref("1069595532@qq.com"); // 新增邮箱
  const gender = ref(1); // 新增性别，默认未知
  const avatarFile = ref(null); // 新增头像文件
  const avatarPreview = ref(""); // 用于头像预览

  const isRegistering = ref(false); // 用于控制注册按钮的加载状态

  // 获取 user store 实例
  const userStore = useUserStore();

  /**
   * 处理头像文件选择
   * @param {File} file - ElUpload 触发的 File 对象
   */
  const handleAvatarChange = (file) => {
    avatarFile.value = file.raw; // ElUpload 会返回一个包装过的对象，我们需要原始的 File 对象
    // 生成预览 URL
    if (file.raw) {
      avatarPreview.value = URL.createObjectURL(file.raw);
    } else {
      avatarPreview.value = "";
    }
  };

  /**
   * 处理注册逻辑
   */
  const handleRegister = async () => {
    // 1. 客户端表单验证
    if (
      userName.value.trim() === "" ||
      userPassword.value.trim() === "" ||
      confirmPassword.value.trim() === ""
    ) {
      ElMessage.warning("账号、密码和确认密码不能为空！");
      return;
    }
    if (userPassword.value !== confirmPassword.value) {
      ElMessage.warning("两次输入的密码不一致！");
      return;
    }
    if (userPassword.value.length < 6 || userPassword.value.length > 100) {
      ElMessage.warning("密码长度必须在6到100个字符之间！");
      return;
    }
    if (userName.value.length < 3 || userName.value.length > 50) {
      ElMessage.warning("账号长度必须在3到50个字符之间！");
      return;
    }
    // 可以在这里添加手机号和邮箱的格式校验
    // 例如，简单的邮箱校验
    if (email.value && !/^\S+@\S+\.\S+$/.test(email.value)) {
      ElMessage.warning("请输入有效的邮箱地址！");
      return;
    }
    // 简单的手机号校验 (只检查是不是数字，更严格的校验请用正则)
    if (mobile.value && !/^\d+$/.test(mobile.value)) {
      ElMessage.warning("请输入有效的手机号！");
      return;
    }

    isRegistering.value = true; // 开始注册，设置加载状态为 true

    try {
      // 2. 构建 FormData 对象
      // 当需要上传文件时，必须使用 FormData
      const formData = new FormData();
      formData.append("userName", userName.value.trim());
      formData.append("userPassword", userPassword.value.trim());
      // 可选字段，只在有值时添加，避免发送空字符串
      if (mobile.value.trim()) {
        formData.append("mobile", mobile.value.trim());
      }
      if (email.value.trim()) {
        formData.append("email", email.value.trim());
      }
      // 性别是数字，即使为0也发送
      formData.append("gender", gender.value);
      // 如果有头像文件，则添加到 FormData
      if (avatarFile.value) {
        formData.append("avatarFile", avatarFile.value);
      }
      // 注意：MyUserDTO 中的 roles 和 userStatus 在注册时通常由后端设置默认值或根据业务逻辑分配，
      // 前端一般不需要在注册表单中提供。如果后端需要，你可以根据需求添加。

      // 3. 调用 Pinia store 中的注册方法
      // 假设 userStore.register 方法现在接收 FormData 对象
      const res = await userStore.register(formData);
      // 重点：在这里检查后端返回的业务状态码
      if (res && res.data.code === 1) {
        // 确保res存在且code为1
        ElMessage.success("注册成功！请登录。");
        router.push("/login"); // 注册成功后跳转到登录页面
      } else {
        // 理论上，如果 res.code 不是 1，store 已经抛出了 Error。
        // 但为了健壮性，如果 store 返回了非成功状态但没有抛出错误（不应该发生），这里可以再处理一次。
        // 不过，根据前面的 store 修改，这里应该只会收到成功的 res，或捕获到 error。
        ElMessage.error(res.msg || "注册失败，请稍后再试。");
      }
    } catch (error) {
      // 5. 处理注册失败的错误
      console.error("注册请求失败:", error);
      const errorMessage =
        error.message || error.response?.data?.msg || "注册失败，请稍后再试。";
      ElMessage.error(errorMessage);
    } finally {
      // 无论成功或失败，最后都重置加载状态
      isRegistering.value = false;
    }
  };

  /**
   * 跳转到登录页面
   */
  const goToLogin = () => {
    router.push("/login");
  };

  /**
   * 跳转到关于页面
   */
  const goToAbout = () => {
    router.push("/about");
  };

  /**
   * 跳转到找回密码页面
   */
  const goToResetPassword = () => {
    router.push("/reset-password");
  };
  </script>

  ---

  <style scoped>
  .register-container {
    height: 100vh;
    display: flex;
    flex-direction: column;
    background-color: white; /* 纯白背景 */
  }

  .register-content {
    flex: 1;
    display: flex;
    flex-direction: column;
    align-items: center;
    padding: 20px;
    margin-top: 20px;
  }

  .logo {
    margin-bottom: 40px;
    display: flex;
    justify-content: center;
  }

  .register-form {
    width: 100%;
    max-width: 300px;
  }

  .input-container {
    margin-bottom: 20px;
  }

  /* 统一输入框样式 */
  :deep(.custom-input .el-input__wrapper) {
    border-radius: 25px;
    padding: 0 20px;
    height: 50px;
    box-shadow: 0 0 0 1px #dcdfe6 inset;
  }

  :deep(.custom-input .el-input__wrapper:hover) {
    box-shadow: 0 0 0 1px #c0c4cc inset;
  }

  :deep(.custom-input .el-input__wrapper.is-focus) {
    box-shadow: 0 0 0 1px #ff5000 inset;
  }

  :deep(.custom-input .el-input__inner) {
    height: 48px;
  }

  /* Element Plus Select 样式 */
  .custom-select {
    width: 100%;
  }
  :deep(.custom-select .el-input__wrapper) {
    border-radius: 25px;
    padding: 0 20px;
    height: 50px;
    box-shadow: 0 0 0 1px #dcdfe6 inset;
  }
  :deep(.custom-select .el-input__wrapper:hover) {
    box-shadow: 0 0 0 1px #c0c4cc inset;
  }
  :deep(.custom-select .el-input__wrapper.is-focus) {
    box-shadow: 0 0 0 1px #ff5000 inset;
  }

  /* 头像上传样式 */
  .avatar-upload-container {
    display: flex;
    flex-direction: column;
    align-items: center;
    margin-bottom: 20px;
  }

  .avatar-uploader .avatar {
    width: 100px;
    height: 100px;
    display: block;
    border-radius: 50%; /* 圆形头像 */
    object-fit: cover;
  }
  .avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 50%; /* 圆形上传区域 */
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
    width: 100px;
    height: 100px;
    display: flex; /* Flexbox for centering icon */
    justify-content: center;
    align-items: center;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #ff5000;
  }
  .el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 100px;
    height: 100px;
    text-align: center;
  }
  .upload-tip {
    margin-top: 10px;
    font-size: 14px;
    color: #606266;
  }

  /* 注册按钮样式 */
  .register-btn {
    width: 100%;
    height: 50px;
    border-radius: 25px;
    background-color: #ff5000;
    border: none;
    font-size: 16px;
    font-weight: bold;
  }

  .register-btn:hover {
    background-color: #ff3a00;
  }

  .login-back-btn {
    width: 100%;
    height: 50px;
    border-radius: 25px;
    background-color: #ffffff;
    border: none;
    font-size: 16px;
    font-weight: bold;
    border: 1px solid #000000;
  }

  .login-back-btn:hover {
    color: #3b3b3b;
    background-color: #f5f5f5;
  }

  /* 覆盖底部导航栏的空白区域 */
  .bottom-cover {
    height: 120px;
    background-color: white;
    z-index: 1000;
    bottom: 0;
    left: 0;
    right: 0;
    display: flex;
    justify-content: center;
    align-items: center;
    padding-bottom: 30px;
  }

  .bottom-links {
    display: flex;
    align-items: center;
    font-size: 14px;
  }

  .bottom-links span {
    cursor: pointer;
    color: #606266;
    transition: color 0.3s;
  }

  .bottom-links span:hover {
    color: #ff5000;
  }

  .bottom-links .divider {
    margin: 0 10px;
    color: #dcdfe6;
    cursor: default;
  }
  </style>